// 游戏初始化测试
// 测试消消乐游戏初始化时是否存在3个以上相同图标连在一起的问题

const gameLogic = {
  // 模拟游戏的图片数据
  imageUrls: [
    '/images/game/sad.jpg',
    '/images/game/home.png',
    '/images/game/history.png',
    '/images/game/stats.png',
    '/images/game/profile.png',
    '/images/game/home-active.png'
  ],
  gridSize: 8,

  // 复制游戏中的findMatches函数逻辑
  findMatches: function(grid) {
    if (!grid || !Array.isArray(grid)) {
      console.error('无效的网格数据');
      return [];
    }
    
    const gridSize = grid.length;
    let matches = [];
    
    // 检查水平匹配
    for (let i = 0; i < gridSize; i++) {
      if (!grid[i] || !Array.isArray(grid[i])) continue;
      
      let j = 0;
      while (j < gridSize - 2) {
        // 确保所有单元格都有有效的imageIndex
        if (j + 2 < grid[i].length && 
            grid[i][j] && grid[i][j+1] && grid[i][j+2] && 
            typeof grid[i][j].imageIndex === 'number' && 
            typeof grid[i][j+1].imageIndex === 'number' && 
            typeof grid[i][j+2].imageIndex === 'number') {
          
          // 检查是否有三个相同的图标
          if (grid[i][j].imageIndex === grid[i][j+1].imageIndex &&
              grid[i][j].imageIndex === grid[i][j+2].imageIndex) {
            
            // 找到水平匹配的三个或更多
            let matchLength = 3;
            while (j + matchLength < gridSize && 
                   j + matchLength < grid[i].length &&
                   grid[i][j + matchLength] && 
                   typeof grid[i][j + matchLength].imageIndex === 'number' &&
                   grid[i][j].imageIndex === grid[i][j+matchLength].imageIndex) {
              matchLength++;
            }
            
            // 添加所有匹配的方块
            for (let k = 0; k < matchLength; k++) {
              const existingMatch = matches.find(m => m.row === i && m.col === j + k);
              if (!existingMatch) {
                matches.push({ row: i, col: j + k, type: 'horizontal', length: matchLength });
              }
            }
            
            j += matchLength;
          } else {
            j++;
          }
        } else {
          j++;
        }
      }
    }
    
    // 检查垂直匹配
    for (let j = 0; j < gridSize; j++) {
      let i = 0;
      while (i < gridSize - 2) {
        // 确保所有单元格都有有效的imageIndex
        if (i + 2 < gridSize &&
            grid[i] && grid[i+1] && grid[i+2] && 
            grid[i][j] && grid[i+1][j] && grid[i+2][j] &&
            typeof grid[i][j].imageIndex === 'number' && 
            typeof grid[i+1][j].imageIndex === 'number' && 
            typeof grid[i+2][j].imageIndex === 'number') {
          
          // 检查是否有三个相同的图标
          if (grid[i][j].imageIndex === grid[i+1][j].imageIndex &&
              grid[i][j].imageIndex === grid[i+2][j].imageIndex) {
            
            // 找到垂直匹配的三个或更多
            let matchLength = 3;
            while (i + matchLength < gridSize && 
                   grid[i + matchLength] && 
                   grid[i + matchLength][j] &&
                   typeof grid[i + matchLength][j].imageIndex === 'number' &&
                   grid[i][j].imageIndex === grid[i+matchLength][j].imageIndex) {
              matchLength++;
            }
            
            // 添加所有匹配的方块
            for (let k = 0; k < matchLength; k++) {
              const existingMatch = matches.find(m => m.row === i + k && m.col === j);
              if (!existingMatch) {
                matches.push({ row: i + k, col: j, type: 'vertical', length: matchLength });
              }
            }
            
            i += matchLength;
          } else {
            i++;
          }
        } else {
          i++;
        }
      }
    }
    
    return matches;
  },

  // 测试用的网格初始化函数（修复后的版本）
  createTestGrid: function() {
    const { gridSize, imageUrls } = this;
    let grid = [];
    
    // 创建一个更安全的交替模式网格，确保没有三个相同的图标连在一起
    for (let i = 0; i < gridSize; i++) {
      let row = [];
      for (let j = 0; j < gridSize; j++) {
        // 使用更复杂的模式来确保相邻位置不会有相同图片
        // 基于棋盘模式，但确保不会产生三连
        let imageIndex = (i * 3 + j * 2) % imageUrls.length;
        
        // 额外检查：如果当前索引可能导致匹配，选择不同的索引
        let attempts = 0;
        while (attempts < imageUrls.length) {
          let hasConflict = false;
          
          // 检查水平冲突
          if (j >= 2 && row[j-1] && row[j-2] && 
              row[j-1].imageIndex === imageIndex && 
              row[j-2].imageIndex === imageIndex) {
            hasConflict = true;
          }
          
          // 检查垂直冲突
          if (i >= 2 && grid[i-1] && grid[i-2] && 
              grid[i-1][j] && grid[i-2][j] &&
              grid[i-1][j].imageIndex === imageIndex && 
              grid[i-2][j].imageIndex === imageIndex) {
            hasConflict = true;
          }
          
          if (!hasConflict) {
            break;
          }
          
          // 尝试下一个索引
          imageIndex = (imageIndex + 1) % imageUrls.length;
          attempts++;
        }
        
        row.push({
          imageUrl: imageUrls[imageIndex],
          imageIndex: imageIndex,
          row: i,
          col: j,
          id: `cell-${i}-${j}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        });
      }
      grid.push(row);
    }
    
    return grid;
  },

  // 运行测试
  runTest: function() {
    console.log('=== 游戏初始化测试开始 ===');
    console.log(`网格大小: ${this.gridSize}x${this.gridSize}`);
    console.log(`图片数量: ${this.imageUrls.length}`);
    
    const testRuns = 10; // 测试10次
    let totalMatches = 0;
    let testResults = [];
    
    for (let test = 1; test <= testRuns; test++) {
      console.log(`\n--- 测试运行 ${test} ---`);
      
      const grid = this.createTestGrid();
      const matches = this.findMatches(grid);
      
      console.log(`发现匹配数量: ${matches.length}`);
      
      if (matches.length > 0) {
        console.log('⚠️  发现初始匹配:');
        matches.forEach((match, index) => {
          console.log(`  匹配 ${index+1}: 位置(${match.row},${match.col}), 类型: ${match.type}, 长度: ${match.length}`);
        });
        totalMatches += matches.length;
      } else {
        console.log('✅ 没有发现初始匹配');
      }
      
      testResults.push({
        test: test,
        matches: matches.length,
        grid: grid
      });
    }
    
    console.log('\n=== 测试总结 ===');
    console.log(`总测试次数: ${testRuns}`);
    console.log(`发现匹配的测试: ${testResults.filter(r => r.matches > 0).length}`);
    console.log(`总匹配数量: ${totalMatches}`);
    console.log(`平均每次测试匹配数: ${(totalMatches / testRuns).toFixed(2)}`);
    
    if (totalMatches === 0) {
      console.log('🎉 所有测试通过！初始化不会产生匹配。');
    } else {
      console.log('❌ 测试发现问题，初始化仍可能产生匹配。');
    }
    
    return {
      success: totalMatches === 0,
      totalMatches: totalMatches,
      testRuns: testRuns,
      results: testResults
    };
  }
};

// 运行测试
gameLogic.runTest();
